package vg.services.graph_view_manager.realization.graph_view.smart_graph_view.realization.patches;

import java.util.ArrayList;
import java.util.Collection;

import vg.services.data_base_manager.data.graph.Edge;
import vg.services.data_base_manager.data.graph.Graph;
import vg.services.data_base_manager.data.graph.Vertex;
import vg.services.data_base_manager.data.header.GraphHeader;
import vg.services.graph_view_manager.realization.graph_view.smart_graph_view.interfaces.ISGVGraphView4Patching;
import vg.services.main_manager.MainManager;

/**
 * This patch creates new visualization for new graph. 
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */

public class NewGraphPatch extends DefaultPatch {
	private Graph graph; 	

	/**
	 * Constructor.
	 */
	public NewGraphPatch(Graph graph) {
		super("New graph");
		this.graph = graph;
	}
	
	@Override
	public void apply(ISGVGraphView4Patching graphView4patching) {
		// load graph
		if (graph != null) {
			graphView4patching.setGraphId(graph.getStorableId());
			
			GraphHeader graph_header = MainManager.model.getGraphHeader(graph.getStorableId());
			if (graph_header != null) {
				graphView4patching.setGraphModelId(graph_header.graph_model_id);
				graphView4patching.setDirected(graph_header.directed);
			}			
			
			long all_element_size = 0;
			long curr_element_size = 0;
			
			Collection<Vertex> vertices = graph.getVertices();
			Collection<Edge> edges = graph.getEdges();
			
			if (vertices != null) all_element_size += vertices.size();
			if (edges != null) all_element_size += edges.size();
			
			if (vertices != null) {
				Collection<Vertex> tmp_vertices = new ArrayList<Vertex>();
				for (Vertex buff : vertices) {
					tmp_vertices.add(buff);
					curr_element_size++;
					if (curr_element_size % 100 == 0) {
						graphView4patching.addVertices(tmp_vertices);
						tmp_vertices.clear();
						progress.setValue((long)((curr_element_size / (double)all_element_size) * 100));
						try {
							Thread.sleep(10);
						} catch (InterruptedException ex) {
							
						}					
					}
				}
				graphView4patching.addVertices(tmp_vertices);
				tmp_vertices.clear();
			}
			
			if (edges != null) {
				Collection<Edge> tmp_edges = new ArrayList<Edge>();
				for (Edge buff : edges) {
					tmp_edges.add(buff);
					curr_element_size++;
					if (curr_element_size % 100 == 0) {
						graphView4patching.addEdges(tmp_edges);
						tmp_edges.clear();
						progress.setValue((long)((curr_element_size / (double)all_element_size) * 100));
						try {
							Thread.sleep(10);
						} catch (InterruptedException ex) {
							
						}					
					}
				}
				graphView4patching.addEdges(tmp_edges);
				tmp_edges.clear();
			}
			
			graphView4patching.refreshView();
		}
		
		// finish load graph
		progress.finish();
	}	
}
